import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useRef, useState, useEffect } from 'react';
import DataForm from './components/DataForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

const Partner = () => {
  const [modal, setModal] = useState([]);
  const { dayCcOrderStore: store } = useStore();
  const dayCcRef = useRef();

  useEffect(() => {
    (async () => {
      await store.getDict('region');
    })();
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  // eslint-disable-next-line no-unused-vars
  const handleOpenAdd = () => {
    dayCcRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = (dayCc) => {
    dayCcRef.current = dayCc;
    setModal(['edit']);
  };

  // 点击删除
  const handleDelete = (dayCc) => {
    confirm({
      title: '确认删除该订单吗?',
      onOk() {
        return store.deleteCcOrder(dayCc.id);
      },
    });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { price, state, remark } = result;
        const newData = [
          `订单价格: ${price}`,
          `订单状态: ${ENUMS.state[state]}`,
          `订单备注: ${remark || '无'}`,
        ];
        const oldData = [
          `订单价格: ${dayCcRef.current?.price || '0'}`,
          `订单状态: ${ENUMS.state[dayCcRef.current?.state]}`,
          `订单备注: ${dayCcRef.current?.remark || '无'}`,
        ];
        await store.update({ ...toJS(result), newData, oldData });
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`合伙人创建成功` });
      } catch (e) {
        Message.error({ content: t`合伙人创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`用车开始时间`, t`用车结束时间`],
            },
          },
          {
            name: 'departureCity',
            type: 'select',
            props: {
              dataSource: store.region,
              placeholder: t`出发城市`,
            },
          },
          {
            name: 'state',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.state),
              placeholder: t`状态`,
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.dayCc)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('customerName', { width: 88 }),
            column('customerPhone', { width: 88 }),
            column('departureCityText', { width: 88 }),
            column('departureStationText', { width: 118 }),
            column('price', { width: 88, cell: (v) => <span>{v ? v?.toFixed(2) : '无'}</span> }),
            column('state', { width: 88 }),
            column('departureTime', { width: 100 }),
            column('crDate', { width: 100 }),
            {
              title: t`操作`,
              dataIndex: 'dayCcOrderNumber',
              width: 180,
              cell: (_, __, cc) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(cc)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(cc)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加包车` : t`修改按天包车【${dayCcRef.current?.customerName}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="70%"
      >
        <DataForm
          ccOrderId={dayCcRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Partner);
